package com.longrise.android.byjk.plugins.dealsituation.course.exercises;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.android.byjk.common.MessageConstants;
import com.longrise.android.byjk.common.SituationControl;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.ReceiverType;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.VideoConsts;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.VideoParams;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.utils.DZZWTools;
import com.longrise.android.byjk.utils.ListenUtil;
import com.longrise.common.utils.NetUtil;
import com.longrise.common.utils.PrintLog;
import com.longrise.android.byjk.utils.Tracker_Google;
import com.longrise.android.byjk.widget.view.BaseFrameView;


/**
 * Created by sujizhong on 2016/11/22.
 * 模拟测试题
 * mainfest中关闭硬件加速
 * todo mvp wait refactor
 */

public class SimulationTestActivity extends Activity implements BaseFrameView.ReloadListener {

    private static final String TAG = "SimulationTestActivity";

    private final String ON_PARAMS_URL = "ON_PARAMS_URL";

    private final int MSG_PAGE_START = 0;
    private final int MSG_PAGE_ERROR = 1;
    private final int MSG_PAGE_FINISH = 2;
    private final int MSG_SIMULATION_TITLE = 3;
    private final int MSG_ACTIVITY_FINISH = 4;
    private final int MSG_TOAST_INFOR = 5;

    private RelativeLayout mRela_Back;
    private TextView mText_Title;

    public WebView mWebView;
    private WebSettings mWebSettings;
    private BaseFrameView mBaseFrameView;

    private boolean mLoadIsError = false;

    private String mUrl = "";  //server返回地址前缀
    private VideoParams mParams;

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int what = msg.what;
            switch (what) {
                case MSG_PAGE_START:
                    try {
                        mWebView.setVisibility(View.GONE);
                        mBaseFrameView.setVisibility(View.VISIBLE);
                        mBaseFrameView.setLoadingStatus(BaseFrameView.LoadingStatus.LOADING);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;

                case MSG_PAGE_ERROR:
                    try {
                        mWebView.setVisibility(View.GONE);
                        mBaseFrameView.setVisibility(View.VISIBLE);
                        mBaseFrameView.setLoadingStatus(BaseFrameView.LoadingStatus.ERROR);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;

                case MSG_PAGE_FINISH:
                    try {
                        mLoadIsError = false;
                        mBaseFrameView.setVisibility(View.GONE);
                        mWebView.setVisibility(View.VISIBLE);
                        mBaseFrameView.setLoadingStatus(BaseFrameView.LoadingStatus.SUCCESS);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;

                case MSG_SIMULATION_TITLE:
                    try {
                        String title = (String) msg.obj;
                        mText_Title.setText(title);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;

                case MSG_ACTIVITY_FINISH:
                    finish();
                    break;

                case MSG_TOAST_INFOR:
                    try {
                        String toast = (String) msg.obj;
                        DZZWTools.showToast(SimulationTestActivity.this, toast, Toast.LENGTH_SHORT);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;

                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle saveState) {
        super.onCreate(saveState);
        if (saveState != null) {
            onRestoreState(saveState);
        } else {
            getExtraData();
        }
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_simulation);
        init();

        Tracker_Google.getInstance().addGoogleScreenName("simulated-exam");
    }

    private void onRestoreState(Bundle saveState) {
        mUrl = saveState.getString(ON_PARAMS_URL);
        mParams = saveState.getParcelable(VideoConsts.VIDEO_PARAMS_PARCELABLE);
    }

    private void getExtraData() {
        Intent extraIntent = getIntent();
        mParams = extraIntent.getParcelableExtra(VideoConsts.VIDEO_PARAMS_PARCELABLE);
    }

    public void init() {
        mRela_Back = (RelativeLayout) findViewById(R.id.relapp_back);
        mText_Title = (TextView) findViewById(R.id.app_title);
        initWebView();
        regEvent();
        if (checkNetwork()) {
            mHandler.sendEmptyMessage(MSG_PAGE_START);
            clientRequest();
        }
    }

    private void initWebView() {
        mBaseFrameView = (BaseFrameView) findViewById(R.id.simulationactivity_baseframeview);
        mBaseFrameView.setOnReloadListener(this);
        mWebView = (WebView) findViewById(R.id.simulationactivity_webview);
        setWebSetting();
    }

    private void clientRequest() {
        EntityBean bean = new EntityBean();
        bean.set("urltype", "mncs");
        EntityBean bean2 = new EntityBean();
        bean2.set("bean", bean);
        LoadDataManager.getInstance().callService(null, UrlConstants.BaseUrl, "bbt_getAppEntryPath", bean2, new LoadDataManager.OnRequestCallListener() {

            @Override
            public void onSuccess(String key, String service, Object result) {
                try {
                    clientParse((EntityBean) result);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                mUrl = "";
                mHandler.sendEmptyMessage(MSG_PAGE_ERROR);
            }

            @Override
            public void onFinished(String key, String service) {
            }

        });
    }

    private void regEvent() {
        if (mRela_Back != null) {
            mRela_Back.setOnClickListener(mOnClickListener);
        }
        if (mText_Title != null) {
            mText_Title.setText("");
        }
    }

    private void setWebSetting() {
        mWebSettings = mWebView.getSettings();

        mWebSettings.setLoadWithOverviewMode(true);
        mWebSettings.setUseWideViewPort(true);
        mWebSettings.setJavaScriptEnabled(true);
        //设置 缓存模式 不用缓存 使用localStorage
        mWebSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebSettings.setDomStorageEnabled(true);
        mWebSettings.setAppCacheMaxSize(1024 * 1024 * 8);
        String absolutePath = getApplicationContext().getCacheDir().getAbsolutePath();
        mWebSettings.setAppCachePath(absolutePath);
        mWebSettings.setAllowFileAccess(true);
        mWebSettings.setAppCacheEnabled(true);
        mWebSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);

        mWebView.setWebViewClient(mWebViewClient);
        mWebView.setWebChromeClient(mWebChromeClient);
        mWebView.addJavascriptInterface(new SimulationJSCallback(), "bb");
    }

    private void clientParse(EntityBean result) throws Exception {
        if (result == null) {
            mUrl = "";
            mHandler.sendEmptyMessage(MSG_PAGE_ERROR);
            return;
        }
        EntityBean bean = result.getBean("result");
        mUrl = bean.getString("simulationtesturl", "");
        if (isEmptyUrl()) {
            mUrl = getUrl(mUrl);
            PrintLog.e(TAG, "mUrl: " + mUrl);
            load(mUrl);
        }
    }

    private boolean isEmptyUrl() {
        if (TextUtils.isEmpty(mUrl)) {
            mUrl = "";
            mHandler.sendEmptyMessage(MSG_PAGE_ERROR);
            return false;
        } else {
            return true;
        }
    }

    private void load(String url) {
        mWebView.loadUrl(url);
    }


    private WebChromeClient mWebChromeClient = new WebChromeClient() {

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (!TextUtils.isEmpty(title) && title.toLowerCase().contains("error")) {
                mLoadIsError = true;
            }
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
        }
    };

    private View.OnClickListener mOnClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            int id = v.getId();
            switch (id) {
                case R.id.relapp_back:
                    onKeyDown(KeyEvent.KEYCODE_BACK, null);
                    break;

                default:
                    break;
            }
        }
    };

    private WebViewClient mWebViewClient = new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            if (checkNetwork()) {
                mHandler.sendEmptyMessage(MSG_PAGE_START);
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (mLoadIsError) {
                mHandler.sendEmptyMessage(MSG_PAGE_ERROR);
            } else {
                mHandler.sendEmptyMessageDelayed(MSG_PAGE_FINISH, 500);
            }
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            mLoadIsError = true;
        }
    };

    @Override
    public void onReload(View v) {
        if (checkNetwork()) {
            mLoadIsError = false;
            if (TextUtils.isEmpty(mUrl)) {
                clientRequest();
            } else {
                load(mUrl);
            }
        }
    }

    private boolean checkNetwork() {
        if (!NetUtil.checkNetEnable()) {
            mHandler.sendEmptyMessage(MSG_PAGE_ERROR);
            return false;
        } else {
            return true;
        }
    }

    private class SimulationJSCallback {

        public SimulationJSCallback() {
        }

        @JavascriptInterface
        public void loadFinish() {
        }

        @JavascriptInterface
        public void shareParams(String title, String sharepath, String sharecontent) {
        }

        @JavascriptInterface
        public void showHintMsg(String msg) {
            if (!TextUtils.isEmpty(msg)) {
                Message toast = new Message();
                toast.what = MSG_TOAST_INFOR;
                toast.obj = msg;
                mHandler.sendMessage(toast);
            }
        }

        @JavascriptInterface
        public void pageBack(boolean isback) {
        }

        @JavascriptInterface
        public void getTitle(String title) {
            if (!TextUtils.isEmpty(title)) {
                Message msgTitle = new Message();
                msgTitle.what = MSG_SIMULATION_TITLE;
                msgTitle.obj = title;
                mHandler.sendMessage(msgTitle);
            }
        }

        @JavascriptInterface
        public void scrollChange(boolean isTop) {
        }

        @JavascriptInterface
        public void showCommentBox() {
        }

        @JavascriptInterface
        public void updateCoursePraxis() {
            //模拟试题通过之后web调用，刷新本地状态
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    ListenUtil.getInstance().setPay(ListenUtil.PLAY_VIDEO_FINISH);//更新CurriclumStudy
                    SituationControl.onDealSiuationLfViewCallBackRe(true);
                    sendRefrushVideo();
                }
            });
        }

        @JavascriptInterface
        public void closeSimulationTest() {
            //根据web对页面调整 关闭当前界面
            mHandler.sendEmptyMessage(MSG_ACTIVITY_FINISH);
        }

        @JavascriptInterface
        public void onPageStarted() {
        }

        @JavascriptInterface
        public void onPageFinished() {
        }
    }

    private void sendRefrushVideo() {
        Intent intent = new Intent(MessageConstants.PAY_SUCCESS);
        intent.putExtra(ReceiverType.RECEIVER_KEY, ReceiverType.REFRESH_DETIAL);
        sendBroadcast(intent);
    }

    private String getUrl(String infodetailsurl) {
        if (mParams == null) {
            return "";
        }
        StringBuilder builder = new StringBuilder();
        builder.append(infodetailsurl);
        builder.append("/@");
        builder.append(mParams.mCwid);
        builder.append("/@");
        builder.append(UserInfor.getInstance().getUsersfzh());
        builder.append("/@");
        builder.append(mParams.mStudentNo);
        builder.append("/@");
        builder.append(mParams.istest);
        builder.append("/@");
        builder.append(mParams.recordid);
        builder.append("/@");
        builder.append(UserInfor.getInstance().getUserid());
        builder.append("/@");
        builder.append(mParams.mCourseId);
        return builder.toString();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            mWebView.loadUrl("javascript:rebackPRE()");
            return true;
        }
        if (event == null) {
            mHandler.sendEmptyMessage(MSG_ACTIVITY_FINISH);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(ON_PARAMS_URL, mUrl);
        outState.putParcelable(VideoConsts.VIDEO_PARAMS_PARCELABLE, mParams);
        mWebView.saveState(outState);
    }

    private void releaseWebView() {
        if (mWebSettings != null) {
            mWebSettings.setJavaScriptEnabled(false);
        }
        if (mWebView != null) {
            mWebView.removeAllViews();
            mWebView.destroy();
        }
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState != null) {
            mWebView.restoreState(savedInstanceState);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        releaseWebView();
    }
}
